/*
@STI LICENSE
(C) 2006-2008 Universit�t Innsbruck.

This file is part of myOntology.

myOntologyis free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

myOntologyis distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with myOntology.  If not, see <http://www.gnu.org/licenses/>.

@STI LICENSE */
package org.myontology.controller;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

public class ValueHandler<T> {

	public static Logger logger = Logger.getLogger(ValueHandler.class);
	
	protected String key;
	protected AttributeLevel level;
	protected Class clazz=null;
	protected Object o=null;
	
	public ValueHandler(AttributeLevel level,Class parent) {
		this.clazz = parent;
		this.level=level;
	}
	
	public ValueHandler(AttributeLevel level,Object o) {
		this.o = o;
		this.level=level;
	}
	
	public void setValue(AttributeHolder attributes,T value) {
		init();
		switch (level) {
		case REQUEST:
			attributes.setRequestAttribute(key, value);
			break;
		case SESSION:
			attributes.setSessionAttribute(key, value);
			break;
		case APPLICATION:
			attributes.setApplicationAttribute(key, value);
			break;
		}
	}
	
	public T getValue(AttributeHolder attributes) {
		init();
		T value=null;
		switch (level) {
		case REQUEST:
			value=(T)attributes.getRequestAttribute(key);
			break;
		case SESSION:
			value=(T)attributes.getSessionAttribute(key);
			break;
		case APPLICATION:
			value=(T)attributes.getApplicationAttribute(key);
			break;
		}
		return value;
	}
	
	public T getValue(HttpServletRequest request) {
		return getValue(new WebAttributeHolder(request));
	}
	
	private void init() {
		if (key!=null)
			return;
		if (clazz==null)
			clazz = o.getClass();
		findKey(clazz,o);
		if (key==null)
			throw new RuntimeException("wrong class handed to ValueHandler: "+clazz.getName());
	}

	/**
	 * @param c
	 */
	private void findKey(Class c,Object object) {
		Field[] f = c.getDeclaredFields();
		for (int i=0;i<f.length;i++) {
			int m = f[i].getModifiers();
			if ((object!=null || Modifier.isStatic(m)) && Modifier.isPublic(m)) {
				try {
					Object val = f[i].get(object);
					if (val==this) {
						if (level.equals(AttributeLevel.APPLICATION))
							key = f[i].getName();
						else
							key = clazz.getName()+"#"+f[i].getName()+"."+Math.random();
						return;
					}
				} catch (Exception e) {
					logger.error(e);
				} 
			}
		}
		if (key==null && c.getSuperclass()!=null) {
			findKey(c.getSuperclass(),object);
		}
	}
	
}
